package com.clp.protocol.modbus_tcp.mb_frame.mb_body.mb_data.resp_ok;

import com.clp.protocol.core.utils.ByteUtil;
import com.clp.protocol.modbus_tcp.definition.CoilSetting;
import com.clp.protocol.modbus_tcp.definition.ConstVal;
import com.clp.protocol.modbus_tcp.definition.MbByteOrder;
import com.clp.protocol.modbus_tcp.mb_frame.mb_body.mb_data.RespOkMbData;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.nio.ByteOrder;
import java.util.Objects;

@Getter
@NoArgsConstructor
@AllArgsConstructor
public class ForceSingleCoilRespOkMbData implements RespOkMbData {
    /**
     * 设置地址
     */
    private int setAddr;
    /**
     * 设置内容
     */
    private CoilSetting coilSetting;

    @Override
    public ForceSingleCoilRespOkMbData initBy(ByteBuf buf) {
        byte[] setAddrBytes = new byte[ConstVal.SET_ADDR_LEN]; buf.readBytes(setAddrBytes);
        this.setAddr = MbByteOrder.setAddrOrder == ByteOrder.BIG_ENDIAN ?
                ByteUtil.bytes2ToIntBE(setAddrBytes) : ByteUtil.bytes2ToIntLE(setAddrBytes);
        byte[] coilSettingBytes = new byte[ConstVal.SET_COIL_LEN]; buf.readBytes(coilSettingBytes);
        this.coilSetting = CoilSetting.gain(coilSettingBytes);
        return this;
    }

    @Override
    public boolean isValid() {
        if (setAddr < 0 || setAddr > 0xFFFF) return false;
        return coilSetting != null;
    }

    @Override
    public void writeTo(ByteBuf buf) {
        throw new UnsupportedOperationException();
    }

    @Override
    public String toString() {
        return "设置地址：" + setAddr + ", 设置内容：" + coilSetting;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ForceSingleCoilRespOkMbData that = (ForceSingleCoilRespOkMbData) o;
        return setAddr == that.setAddr && coilSetting == that.coilSetting;
    }

    @Override
    public int hashCode() {
        return Objects.hash(setAddr, coilSetting);
    }
}
